#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t cond;
int ticket = 10;

void* Getticket(void* arg)
{
    const char* name = (char*)arg;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        while(ticket <= 0)
        {
            printf("%s waiting for tickets...\n", name);
            pthread_cond_wait(&cond,&mutex);
        }
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s finish get ticket : %d\n",name,ticket--);
            //解鎖
            pthread_mutex_unlock(&mutex);
        }
        pthread_mutex_unlock(&mutex);
    }
    printf("%s quit\n", name);
    pthread_exit((void*)0);
}

int main()
{
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_t p1,p2,p3;
    pthread_create(&p1, NULL, Getticket,"thread-1");
    pthread_create(&p2, NULL, Getticket,"thread-2");
    pthread_create(&p3, NULL, Getticket,"thread-3");

    pthread_join(&p1, NULL);
    pthread_join(&p2, NULL);
    pthread_join(&p3, NULL);

    while(1)
    {
        getchar();
        pthread_cond_signal(&cond);
    }

    pthread_mutex_destroy(&mutex);;
    pthread_cond_destroy(&cond);

    return 0;
}